package com.mxchip.livestar

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import com.mxchip.livestar.base.SystemData
import com.mxchip.livestar.repository.RoomClientRepository
import com.tbruyelle.rxpermissions2.RxPermissions
import com.trello.lifecycle2.android.lifecycle.AndroidLifecycle
import com.trello.rxlifecycle3.LifecycleProvider
import com.umeng.analytics.MobclickAgent
import com.mxchip.livestar.utils.FileLog
import com.mxchip.livestar.utils.MyLog
import com.mxchip.livestar.utils.Utils
import com.mxchip.livestar.ui.network.wifi.view.WifiActivity
import com.videohigh.graham.LoginCallback
import com.videohigh.graham.SampleSDK
import com.videohigh.graham.Term
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.*

class WelcomeActivity : AppCompatActivity() {
    private val logger = FileLog.getLogger(WelcomeActivity::class.java)
    private val provider: LifecycleProvider<Lifecycle.Event> = AndroidLifecycle.createLifecycleProvider(this)
    private val dialog: AlertDialog by lazy {
        AlertDialog.Builder(this)
                .setTitle(getString(R.string.tips))
                .setMessage(getString(R.string.check_net))
                .setPositiveButton(getString(R.string.try_again)) { dialog, which ->
                    getTermId()
                }.setNegativeButton("网络设置") { _, _ ->
                    logger.info("WelcomeActivity::click wlan")
                    startActivity(Intent(this, WifiActivity::class.java))
                }.setCancelable(false).create()
    }

    //查看权限
    private val permisssion: Unit
        get() {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
                        && ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
                        && ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
                        && ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
                        && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
                        && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                        && ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED
                        && ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_CONTACTS) == PackageManager.PERMISSION_GRANTED
                        && ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CALL_LOG) == PackageManager.PERMISSION_GRANTED
                        && ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_CALL_LOG) == PackageManager.PERMISSION_GRANTED) {
                    MyLog.logD(MyLog.WELCOME_ACTIVITY_MODEL,"WelcomeActivity::" + "getPermisssion: ")
                    distributionNumber()
                } else {
                    MyLog.logD(MyLog.WELCOME_ACTIVITY_MODEL,"WelcomeActivity::" + "getPermisssion: ")
                    showPermissionTip()
                }
            }
        }

    @SuppressLint("CheckResult")
    private fun distributionNumber() {



        getTermId()
//        Observable.create { emitter: ObservableEmitter<Any?> ->
//                    startService(Intent(this@WelcomeActivity, MyService::class.java))
//                    Thread.sleep(1000)
//                    while (checkDeviceId()) {
//                        Thread.sleep(1000)
//                    }
//                    emitter.onNext("")
//                }
//                .compose(provider.bindToLifecycle())
//                .compose(RxSchedulersHelper.io_main())
//                .subscribe({ turnToMainActivity() }) { error -> toast("出错了。。。$error") }
    }

    // private val luxxRest = Rest(AppConstant.LUXX_ACCESS_ID, AppConstant.LUXX_ACCESS_SECRET)

    private fun getTermId() {
        lifecycleScope.launch {

            RoomClientRepository.login(object : LoginCallback {
                override fun onSuccess(myTerm: Term, SNCode: String) {
                    /*SPreference.setDeviceNumber(data.number)
                    SPreference.setDeviceRoomId(data.roomId)
                    SPreference.setDeviceToken(data.token)*/
                    // SystemData.userId() = it.body.number

                    SystemData.setDeviceId(SNCode)
                    SystemData.setMyTerm(myTerm)

                    logger.info(SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(Date()) +"WelcomeActivity::getTermId:SNCode:$SNCode myTerm:$myTerm")
                    turnToMainActivity()
                }

                override fun onFailure(code: Int, message: String) {
                    logger.info(SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(Date()) +"WelcomeActivity::getTermId: it.body:${message}  ")
                    runOnUiThread {
                        if (!dialog.isShowing)
                            dialog.show()
                    }
                }
            })

            /*luxxRest.getDeviceToken(SystemData.deviceId(), 60 * 60 * 24 * 365, object : RespCallback<TokenResp> {
                override fun onError(code: Int, message: String) {
                    logger.info(SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(Date()) +"WelcomeActivity::getTermId: it.body:${message}  ")
                    runOnUiThread {
                        if (!dialog.isShowing)
                            dialog.show()
                    }
                }

                override fun onRespData(data: TokenResp) {
                    SPreference.setDeviceNumber(data.number)
                    SPreference.setDeviceRoomId(data.roomId)
                    SPreference.setDeviceToken(data.token)
                    // SystemData.userId() = it.body.number
                    logger.info(SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(Date()) +"WelcomeActivity::distributionNumber: ${data}")
                    turnToMainActivity()
                }
            })*/
        }
    }

    private fun checkDeviceId(): Boolean {
        val s = Utils.checkUserState()
        return s.isNullOrEmpty() || s.length <= 8
    }

    private fun turnToMainActivity() {
        jumpMainActivity()
        finish()
    }

    override fun onResume() {
        super.onResume()
        MobclickAgent.onResume(this)
        permisssion
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        logger.info("WelcomeActivity::onNewIntent:")
        distributionNumber()
    }

    override fun onPause() {
        super.onPause()
        MobclickAgent.onPause(this)
    }

    private fun jumpMainActivity() {
        startActivity(Intent(this, MainActivity::class.java))
    }

    @SuppressLint("CheckResult")
    private fun showPermissionTip() {

        RxPermissions(this).request(*PERMISSIONS)
                .compose(provider.bindToLifecycle())
                .subscribe({ granted ->
                    if (granted) { //                        setResult(PERMISSIONS_GRANTED);
                        MyLog.logD(MyLog.WELCOME_ACTIVITY_MODEL,"WelcomeActivity::" + "showPermissionTip: RxPermissions jumpMainActivity")
                        distributionNumber()
                    } else {
                        setResult(PERMISSIONS_DENIED)
                        finish()
                    }
                }) { error: Throwable -> Log.e(TAG, "showPermissionTip: " + error.message) }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_permission)


    }

    companion object {
        private const val TAG = "WelcomeActivity"

        private val PERMISSIONS = arrayOf(
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.CAMERA,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.READ_CONTACTS,
                Manifest.permission.WRITE_CONTACTS,
                Manifest.permission.READ_CALL_LOG,
                Manifest.permission.WRITE_CALL_LOG,
                Manifest.permission.ACCESS_FINE_LOCATION)

        private const val PERMISSIONS_DENIED = 1
        private const val PERMISSIONS_GRANTED = 0
    }
}